package com.kl.websocket;

import com.kl.websocket.disruptor.*;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * Created by kl on 2018/8/24.
 * Content :Disruptor 环形队列
 */
@Component
public class LoggerDisruptorQueue {

    @Autowired
    private LoggerEventHandler eventHandler;

    private Executor executor = Executors.newCachedThreadPool();

    private LoggerEventFactory factory = new LoggerEventFactory();

    private int bufferSize = 2 * 1024;

    private Disruptor<LoggerEvent> disruptor = new Disruptor<>(factory, bufferSize, executor);

    private static  RingBuffer<LoggerEvent> ringBuffer;

    @PostConstruct
    public void init() {
        disruptor.handleEventsWith(eventHandler);
        ringBuffer = disruptor.getRingBuffer();
        disruptor.start();
    }

    public static void publishEvent(LoggerMessage log) {
        long sequence = ringBuffer.next();
        try {
            LoggerEvent event = ringBuffer.get(sequence);
            event.setLog(log);
        } finally {
            ringBuffer.publish(sequence);
        }
    }

}
